/*
 * Copyright ©2017 贾维程. All rights reserved.
 */

package org.handover.controller.handover;

import org.handover.domain.Details;
import org.handover.domain.Handover;
import org.handover.domain.User;
import org.handover.repository.DetailsRepository;
import org.handover.repository.HandoverRepository;
import org.handover.repository.ShiftRepository;
import org.handover.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Controller
@RequestMapping("/handover/")
//@SessionAttributes(types = {Shift.class},value = {"shift"})
//@SessionAttributes(value={"page","pageSize"})
public class HandoverController {

    @Autowired
    HandoverRepository handoverRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    DetailsRepository detailsRepository;
    @Autowired
    ShiftRepository shiftRepository;

    @RequestMapping("add")
    public String add(Model model) {
        List<User> userList = userRepository.findAllByEnable(true);

        LocalDateTime now = LocalDateTime.now();

        ZoneId zone = ZoneId.systemDefault();
        Instant instant = now.atZone(zone).toInstant();
        Date date = Date.from(instant);

        Handover handover = new Handover();
        handover.setDate(date);

        Integer who = 0;
        if (now.getHour() <= 16) {
            who = 0;
            handover.setShift(shiftRepository.getOne(Long.valueOf(1)));
        }
        else
        {
            who = 1;
            handover.setShift(shiftRepository.getOne(Long.valueOf(2)));
        }
        //System.out.println(who);
        boolean isFind = false;
        for(User user : userList) {
            Date date2;
            try {
                date2 = new SimpleDateFormat("yyyy-MM-dd").parse(user.getUserInformation().getMorningDate().toString());
            } catch (ParseException e) {
                break;
            }
            if (0 == ChronoUnit.DAYS.between(now.toLocalDate(), date2.toInstant().atZone(zone).toLocalDate().plusDays(who))%3){
                handover.setUser(user);
                isFind = true;
                break;
            }
        }
        if (!isFind) {
            if (!userList.isEmpty() && userList.size() > 0) {
                handover.setUser(userList.get(0));
            }
        }
        model.addAttribute("shiftList", shiftRepository.findAll());
        model.addAttribute("userList", userList);
        model.addAttribute(handover);
        return "handover/edit";
    }

    @GetMapping("edit")
    public String list(Model model, Long id){
        model.addAttribute(handoverRepository.getOne(id));
        model.addAttribute("userList", userRepository.findAllByEnable(true));
        model.addAttribute("shiftList", shiftRepository.findAll());
        return "handover/edit";
    }

    @PostMapping("edit")
    @Transactional
    public String save(@Validated Handover handover, BindingResult bindingResult,Model model) {

        //校验是否有错误
        if (bindingResult.hasErrors()) {
            model.addAttribute("userList", userRepository.findAllByEnable(true));
            model.addAttribute("shiftList", shiftRepository.findAll());
            return "handover/edit";
        }

        //检查交接是否存在
        if (null == handover.getId()) {
            if (handoverRepository.existsByDateAndShiftId(handover.getDate(), handover.getShift())) {
                bindingResult.rejectValue("date", "handover.dateandshift.exist", "这个日期班次的交接已经存在了");
                model.addAttribute("userList", userRepository.findAllByEnable(true));
                model.addAttribute("shiftList", shiftRepository.findAll());
                return "handover/edit";
            }
        } else if (handoverRepository.existsByIdNotAndDateAndShiftId(handover.getId(), handover.getDate(), handover.getShift())) {
            bindingResult.rejectValue("date", "handover.dateandshift.exist", "这个日期班次的交接已经存在了");
            model.addAttribute("userList", userRepository.findAllByEnable(true));
            model.addAttribute("shiftList", shiftRepository.findAll());
            return "handover/edit";
        }

        //检查是否有交接内容
        boolean hasDetail = false;
        for (Details details : handover.getDetailsList()) {
            if (null != details.getDetail() && details.getDetail().trim().length() > 0) {
                hasDetail = true;
                break;
            }
        }
        if (!hasDetail) {
            bindingResult.rejectValue("temperature", "handover.detailList.empty", "没有交接内容");
            model.addAttribute("userList", userRepository.findAllByEnable(true));
            model.addAttribute("shiftList", shiftRepository.findAll());
            return "handover/edit";
        }

        //删除空交接内容
        Iterator<Details> iterator = handover.getDetailsList().iterator();
        while (iterator.hasNext()) {
            Details details = iterator.next();
            if (details.getId() != null && details.getDetail().trim().length() == 0) {
                detailsRepository.delete(details);
                iterator.remove();
            } else if (details.getDetail().trim().length() > 0) {
                details.setHandover(handover);
            } else {
                iterator.remove();
            }
        }

        //保存返回
        handoverRepository.save(handover);
        return "redirect:/handover/list";
    }
}
